package com.logic.landseaserver.models.news.service;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.logic.common.domain.Code;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandeaConstants.NewsType;
import com.logic.landseaserver.common.config.FileConfiguration;
import com.logic.landseaserver.common.exception.LandseaException;
import com.logic.landseaserver.common.exception.ResultCodes.CommonResultCode;
import com.logic.landseaserver.common.exception.ResultCodes.NewsResultCode;
import com.logic.landseaserver.common.util.Base64;
import com.logic.landseaserver.common.util.DateUtil;
import com.logic.landseaserver.common.util.FileTool;
import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.domain.News;
import com.logic.landseaserver.models.news.bean.AllNewsResp;
import com.logic.landseaserver.models.news.bean.CodeResp;
import com.logic.landseaserver.models.news.bean.DateResp;
import com.logic.landseaserver.models.news.bean.NewsResp;
import com.logic.landseaserver.persistence.read.NewsReadMapper;
import com.logic.landseaserver.persistence.write.NewsWriteMapper;
import com.logic.system.domain.SystemFile;
import com.logic.system.persistence.read.CodeReadMapper;
import com.logic.system.service.impl.FileService;
/**
 * 
 *
 * 项目名称：system-server</br>
 * 类名称：NewsService</br>
 * 类描述：新闻大事记招采</br>
 * 创建人：Crystal</br>
 * 创建时间：2018年03月21日 下午5:15:40</br>
 * 
 * @version 1.0
 *
 */
@Service
public class NewsService 
{
	private static final Logger LOGGER = LoggerFactory.getLogger(NewsService.class);

	@Autowired
	private NewsReadMapper newsReadMapper;

	@Autowired
	private NewsWriteMapper newsWriteMapper;

	@Autowired
	private FileConfiguration fileConfiguration;

	@Autowired
	private FileService fileService;

	@Autowired
	private CodeReadMapper codeReadMapper;

	public void saveNews(News req) throws LandseaException
	{
		try 
		{
			if (StringUtils.isEmpty(req.getType())) 
			{
				throw LandseaException.createException(NewsResultCode.E012410001);
			}
			//新增
			if (null == req.getId()) 
			{
				if (NewsType.NEW.equals(req.getType()) || NewsType.MEMORABILIA.equals(req.getType())) 
				{

					String name = getName(req.getContent(),req.getType());
					req.setContent(name);
				}
				if (NewsType.RECRUIT.equals(req.getType()) 
						&& StringUtils.isEmpty(req.getRecruitType())) 
				{
					throw LandseaException.createException(NewsResultCode.E012410002);
				}
				req.setWid(StringTools.generateUuid());
				req.initCommonField();
				newsWriteMapper.insertSelective(req);
			}
			//修改
			else
			{
				News resp = newsReadMapper.selectByPrimaryKey(req.getId());
				if (null != resp ) 
				{
					if (resp.getStatus()) 
					{
						throw LandseaException.createException(NewsResultCode.E012410004);
					}
				}
				if (NewsType.NEW.equals(req.getType()) || NewsType.MEMORABILIA.equals(req.getType())) 
				{

					String name = getName(req.getContent(),req.getType());
					req.setContent(name);
				}
				if (NewsType.RECRUIT.equals(req.getType()) 
						&& StringUtils.isEmpty(req.getRecruitType())) 
				{
					throw LandseaException.createException(NewsResultCode.E012410002);
				}
				req.editInitCommonField();
				newsWriteMapper.updateByPrimaryKeySelective(req);
			}
		} 
		catch (LandseaException e)
		{
			throw e;
		}
		catch (Exception e) 
		{
			LOGGER.error("保存新闻消息失败", e);
			throw LandseaException.createException(NewsResultCode.E012510001);
		}
	}

	private String getName(String content, String type) throws LandseaException
	{
		String local = fileConfiguration.getLocal();
		String newPath = fileConfiguration.getNewPath();
		content = Base64.decode(content);
		Date nowTime = new Date();
		String time = DateUtil.convertWeBankTime(nowTime);
		String fileName = new String();
		if (NewsType.NEW.equals(type)) 
		{
			fileName = "NEW"+time +".html";
		}
		else if (NewsType.MEMORABILIA.equals(type)) 
		{
			fileName = "MEMORABILIA"+time +".html";
		}
		String filepath = local + File.separator + newPath;
		//filepath = "G://uploads//html";
		File file = new File(filepath);
		// 如果文件夹不存在则创建
		if (!file.exists() && !file.isDirectory())
		{
			boolean mkdirResult  = file.mkdirs();
			if (!mkdirResult)
			{
				LOGGER.error("createHtml|创建临时文件夹失败.filepath=" + filepath);
				throw LandseaException.createException(CommonResultCode.E00050004);
			}
		}
		FileTool.createFileWithContent(filepath, fileName, content);
		//String newUrl =newPath + File.separator + fileName;
		return fileName;
	}

	public List<NewsResp> selectNewsList(QueryUtil queryUtil)throws LandseaException
	{
		try 
		{
			List<NewsResp> resultResps = newsReadMapper.selectNewsList(queryUtil);
			return resultResps;
		} 
		catch (Exception e) 
		{
			LOGGER.error("新闻招采大事记分页查询失败", e);
			throw LandseaException.createException(NewsResultCode.E012510002);
		}
	}

	public NewsResp getNewsDetail(Integer id) throws LandseaException
	{
		try 
		{
			NewsResp resultResp = newsReadMapper.getNewsDetail(id);
			return resultResp;
		} 
		catch (Exception e) 
		{
			LOGGER.error("查询新闻详情失败", e);
			throw LandseaException.createException(NewsResultCode.E012510003);
		}
	}

	public void editStatus(News req)throws LandseaException
	{
		try 
		{
			News resp = new News();
			resp.setId(req.getId());
			resp.setStatus(req.getStatus());
			resp.editInitCommonField();
			newsWriteMapper.updateStatus(resp);
		} 
		catch (Exception e) 
		{
			LOGGER.error("发布/取消发布新闻失败", e);
			throw LandseaException.createException(NewsResultCode.E012510004);
		}
	}

	public void deleteNews(Integer id) throws LandseaException
	{
		try 
		{
			News resp = newsReadMapper.selectByPrimaryKey(id);
			if (null != resp ) 
			{
				if (resp.getStatus()) 
				{
					throw LandseaException.createException(NewsResultCode.E012410004);
				}
			}
			resp.editInitCommonField();
			newsWriteMapper.deleteByPrimaryKey(resp);
		} 
		catch (LandseaException e)
		{
			throw e;
		}
		catch (Exception e) 
		{
			LOGGER.error("删除新闻失败", e);
			throw LandseaException.createException(NewsResultCode.E012510005);
		}

	}

	public List<NewsResp> selectMemorabilia()  throws LandseaException
	{
		try 
		{
			List<NewsResp> resultResps = newsReadMapper.selectMemorabilia();
			return resultResps;
		} 
		catch (Exception e) 
		{
			LOGGER.error("关于朗诗寓大事记查询失败", e);
			throw LandseaException.createException(NewsResultCode.E012510006);
		}
	}

	public List<NewsResp> selectNew() throws LandseaException
	{
		try 
		{
			List<NewsResp> resultResps = newsReadMapper.selectNew();
			return resultResps;
		} 
		catch (Exception e) 
		{
			LOGGER.error("关于朗诗寓新闻查询失败", e);
			throw LandseaException.createException(NewsResultCode.E012510007);
		}
	}

	public DateResp selectDate(String type) throws LandseaException
	{
		try 
		{
			DateResp resultResp = new DateResp();
			List<String> year = newsReadMapper.selectDate(type);
			resultResp.setYear(year);
			if (NewsType.RECRUIT.equals(type)) 
			{
				List<CodeResp> recruitResp = new ArrayList<>();
				List<Code> systemCodes = codeReadMapper.selectChildrenByParent(NewsType.RECRUIT);
				if(CollectionUtils.isNotEmpty(systemCodes))
				{
					for (Code code : systemCodes)
					{
						CodeResp resp = new CodeResp();
						resp.setCode(code.getCode());
						resp.setCodeName(code.getCodeDescZh());
						recruitResp.add(resp);
					}
				}
				resultResp.setRecruitResp(recruitResp);
			}
			return resultResp;
		} 
		catch (Exception e) 
		{
			LOGGER.error("查询年份日期失败", e);
			throw LandseaException.createException(NewsResultCode.E012510008);
		}
	}

	public AllNewsResp selectAllNews(QueryUtil queryUtil)throws LandseaException
	{
		try 
		{
			AllNewsResp resultResp = new AllNewsResp();
			if ("全部".equals(queryUtil.getParams().get("date"))) 
			{

				queryUtil.getParams().put("date", null);
			}
			if ("全部".equals(queryUtil.getParams().get("recruitType"))) 
			{

				queryUtil.getParams().put("recruitType", null);
			}
			List<NewsResp> resultResps = newsReadMapper.selectAllNews(queryUtil);
			if (CollectionUtils.isNotEmpty(resultResps)) 
			{
				for (NewsResp newsResp : resultResps) 
				{
					if (null != newsResp.getPicture()) 
					{
						SystemFile file = (SystemFile)fileService.get(newsResp.getPicture());
						if (null != file) 
						{
							newsResp.setPicturePath(file.getFullPath());
						}
					}
					if (null != newsResp.getFileId()) 
					{
						SystemFile file = (SystemFile)fileService.get(newsResp.getFileId());
						if (null != file) 
						{
							newsResp.setFilePath(file.getFullPath());
						}
					}
				}
			}
			resultResp.setNewsResps(resultResps);
			//获取总数
			List<Integer> ids = newsReadMapper.selectCount((String)queryUtil.getParams().get("type"),
					(String)queryUtil.getParams().get("date"),
					(String)queryUtil.getParams().get("recruitType"));
			resultResp.setCount(ids.size());
			return resultResp;
		} 
		catch (Exception e) 
		{
			LOGGER.error("查询前端展示新闻大事记招采失败", e);
			throw LandseaException.createException(NewsResultCode.E012510009);
		}
	}
}
